const { pool } = require("../../db");

// 获取全部职位权限数据
exports.getRolePermission = async (roleName, offset, limit) => {
  const query = `select * from roles where roleName like '%${roleName}%' limit ${offset}, ${limit}`;
  const query1 = `select count(*) from roles where roleName like '%${roleName}%'`;
  try {
    const [rows] = await pool.query(query);
    const [count] = await pool.query(query1);
    return { code: 200, data: rows, total: count[0]["count(*)"] };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};

// 获取要分配的权限数据
exports.getPermission = async (id) => {
  const query = `SELECT * FROM menus `;
  const query1 = `SELECT m.* FROM roles_menus rm JOIN menus m ON rm.menu_id = m.id WHERE rm.role_id = ${id};`;
  try {
    const [rows] = await pool.query(query);
    const result = generateNestedData(rows, null);
    const [rows1] = await pool.query(query1);
    const result1 = generateNestedData(rows1, null);
    return { code: 200, data: result, select: result1 };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};
function generateNestedData(data, parentId) {
  const result = [];

  for (const item of data) {
    if (item.parent_id === parentId) {
      const children = generateNestedData(data, item.id);
      if (children.length > 0) {
        item.children = children;
      }
      result.push(item);
    }
  }

  return result;
}

// 添加职位
exports.addRole = async (roleName) => {
  const query = `INSERT INTO roles (rolename) VALUES ('${roleName}')`;
  try {
    await pool.query(query);
    return { code: 200, msg: "添加成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};

// 修改职位
exports.editRole = async (id, roleName) => {
  const query = `UPDATE roles SET rolename = '${roleName}' WHERE id = ${id}`;
  try {
    await pool.query(query);
    return { code: 200, msg: "修改成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};

// 删除职位
exports.deleteRole = async (id) => {
  const query = `DELETE roles, roles_menus FROM roles LEFT JOIN roles_menus ON roles.id = roles_menus.role_id WHERE roles.id = ${id};`;
  try {
    await pool.query(query);
    return { code: 200, msg: "删除成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};

// 修改职位权限
exports.editRolePermission = async (roleId, permissionId) => {
  const permission = permissionId.split(",");
  const values = permission.map((menuId) => [roleId, menuId]);
  try {
    await pool.query(`delete from roles_menus where role_id=${roleId}`);
    await pool.query(`insert into roles_menus (role_id, menu_id) values ?`, [
      values,
    ]);
    return { code: 200, msg: "菜单权限更新成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};
